package com.newtouch.cq.security.token;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.newtouch.cq.lang.util.ServletUtils;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

public interface GenericTokenResolveAble extends Serializable {
	
	String resolveToken(HttpServletRequest request);
	
	default List<String> resolveTokenDetail() {
		String auth_token = resolveToken(ServletUtils.getRequest());
		return resolveTokenDetail(auth_token);
	}
	
	default  List<String> resolveTokenDetail(String token) {
		if (StrUtil.isBlank(token)) {
            return CollUtil.newArrayList();
        }
        List<String> tokenInfoArr = StrUtil.split(token,',');
		if(tokenInfoArr.size() < 2) {
        	return CollUtil.newArrayList();
		}
		return tokenInfoArr;
	}
	
	default WebAuthenticationDetails resolveDetails(HttpServletRequest request, String sessionId) {
		String remoteAddress = ServletUtil.getClientIP(request);
		WebAuthenticationDetails details = new WebAuthenticationDetails(request);
		try {
			Field f = ReflectionUtils.findField(WebAuthenticationDetails.class, "remoteAddress");
			f.setAccessible(true);
			f.set(details, remoteAddress);
			f = ReflectionUtils.findField(WebAuthenticationDetails.class, "sessionId");
			f.setAccessible(true);
			f.set(details, sessionId);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			//不做处理
			return null;
		}
		return details;
	}

}
